#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import logging
import time
import os

from ..settings import Settings
from logging import FileHandler
from io import StringIO


class Logger:
    def __init__(self, logger_name="punittest"):
        self.logger = logging.getLogger(logger_name)
        # 将log放入StringIO，最后由HTMLTestRunner读取，也由其创建文件
        self.logger.log_capture = StringIO()
        logging.root.setLevel(logging.NOTSET)
        self.log_formatter = None

    def init_log_formatter(self, format_text):
        self.log_formatter = logging.Formatter(format_text)

    def add_console_handler(self, level):
        console_handler = logging.StreamHandler()
        console_handler.setLevel(level)
        console_handler.setFormatter(self.log_formatter)
        self.logger.addHandler(console_handler)

    def add_file_handler(self, level, log_dir):
        now_time = time.strftime("%Y-%m-%d_%H-%M-%S")
        self.logger.log_file_name = '{0}.log'.format(now_time)
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        log_file_path = os.path.join(log_dir, self.logger.log_file_name)
        file_handler = FileHandler(filename=log_file_path, delay=True, encoding='utf-8')
        file_handler.setLevel(level)
        file_handler.setFormatter(self.log_formatter)
        self.logger.addHandler(file_handler)

    def add_report_handler(self, level):
        # 将Log放入StringIO，最后由HTMLTestRunner读取
        report_handler = logging.StreamHandler(getattr(self.logger, 'log_capture'))
        report_handler.setLevel(level)
        report_handler.setFormatter(self.log_formatter)
        self.logger.addHandler(report_handler)

    def get_simple_logger(self):
        formatter_text = '[%(asctime)s][%(levelname)s]: %(message)s'
        self.logger.handlers.clear()
        self.init_log_formatter(formatter_text)
        self.add_console_handler("DEBUG")
        return self.logger

    def get_default_logger(self):
        self.logger.handlers.clear()
        self.init_log_formatter(Settings.LOG_FORMAT)

        if Settings.LOG_CONSOLE_SWITCH:
            self.add_console_handler(Settings.LOG_CONSOLE_LEVEL)

        if Settings.LOG_FILE_SWITCH:
            self.add_file_handler(Settings.LOG_FILE_LEVEL, Settings.LOG_DIR)

        if Settings.LOG_REPORT_SWITCH:
            self.add_report_handler(Settings.LOG_REPORT_LEVEL)

        return self.logger

    def get_logger(self):
        if self.logger.handlers:
            return self.logger
        else:
            return self.get_simple_logger()


logger = Logger().get_logger()
